<?php
require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';
require_once dirname(__FILE__). '/util/util.php';
set_time_limit(360*60);
ini_set('memory_limit', '512M');

$g_start = microtime(true);

if (count($argv) != 3)
{
	echo "Usage: php unsub [Site ID] [CSV File Name]\n";
	exit;
}
$dbconn = Connection::getInstance();

$filename = $argv[2];
$file = fopen($filename, 'r');
if (!$file)
{
	echo "Could not open file: ". $filename . "\n";
	exit;
}
if ($file)
{
	$c = 0;
	while ($line = fgets($file))
	{
		//get user info
		$userInfo = getUser($dbconn, trim($line), $argv[1]);
		//check user.unsub
		if(isset($userInfo[0]['unsub']) && $userInfo[0]['unsub'] == 1){
			//do unsub
			$ret = unsub(trim($line), $userInfo[0]);
			$c ++;
			//echo result
			echo $c . "\t". trim($line). "\t". (($ret['allInBoxUnsub'] == 1)?'allinbox success':'') . "\t". (($ret['resultsGenerationUnsub'] == 1)?'results generation success':'') . "\t". "\n";	
		}
	}
	fclose($file);
}

echo 'Totally: '. (microtime(true) - $g_start) . " seconds \n";
echo "memory: " . memory_get_peak_usage() . " bytes \n";

/**
 * get user info
 * @param connection $db
 * @param string $email
 * @param int $site
 * @return array
 */
function getUser($db, $email, $site)
{
	$sql = "SELECT u.unsub AS unsub, u.ip AS ip, s.domain AS siteurl FROM users u LEFT JOIN sites s ON u.site_id=s.id WHERE u.email=? and u.site_id=?";
	try
	{
		$result = $db->query($sql, array($email, $site));
		return $result;
	}
	catch (Exception $e)
	{
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

/**
 * do unsub
 * @param $email
 * @param $userInfo
 * @return array
 */
function unsub($email, $userInfo)
{
	$allInBoxUnsub = allInBoxUnsub($email, $userInfo);
	$resultsGenerationUnsub = resultsGenerationUnsub($email, $userInfo);
	return array("allInBoxUnsub"=>$allInBoxUnsub, "resultsGenerationUnsub"=>$resultsGenerationUnsub);
}

/**
 * allinbox api unsub
 * @param $email
 * @param $usersInfo
 * @return bool
 */
function allInBoxUnsub($email, $userInfo)
{
	$sourceIdArray = array('cashdazzle.com' => '302', 
						   'lalaloot.com' => '303',
						   'mommymoolah.com' => '304'
						  );
	
	$params = array();
	$params['source_id'] = $sourceIdArray[strtolower(trim($userInfo['siteurl']))];
	$params['api_key'] = '360db9dc_aea8_4265_bec6_5735d1e09f1e';
	$params['email'] = trim($email);
	
	$ch = curl_init();
	$url = "https://api.all-inbox.com/?";
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, "resource=unsubscribe&" . http_build_query($params, '', '&'));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	$content_xmlstr = curl_exec($ch);
	$content_obj = simplexml_load_string($content_xmlstr);
	curl_close($ch);
	if(!isset($content_obj->error)){
		return 1;
	}else{
		return 0;
	}
}

/**
 * results_generation api unsub
 * @param $email
 * @param $userInfo
 * @return bool
 */
function resultsGenerationUnsub($email, $userInfo)
{
	$params = array();
	$params['Command'] = 'ManageList';
	$params['ListCode'] = '98Bxu1D1C2MNx';
	$params['EmailAddress'] = trim($email);
	$params['Type'] = 'Unsubscribe';
	$params['ReturnType'] = 'Code';
	$params['SinupIp'] = long2ip($userInfo['ip']);;
	$params['Source'] = $userInfo['siteurl'];
	
	$ch = curl_init();
	$url = "https://api.resultsgeneration.com/api.php?&" . http_build_query($params, '', '&');

	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	$content = curl_exec($ch);
	curl_close($ch);
	if(strtolower(trim($content)) == 'success'){
		return 1;
	}else{
		return 0;
	}
}
?>